<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div style="width: 100%;">
    <div style="width: 100%;">
      <div style="display: flex; padding: 1px 15px;align-items: center;">
        <!-- 组件1 : 新增按钮 + 菜单名称 -->
        <el-button type="primary" @click="add">新建</el-button>
        <span style="margin-left: 10px; font-size: 20px;">部门</span>
        <div style="margin-left: auto;margin-right: auto;">
          <!-- 搜索框 -->
          <ISearch :fieldsConfig="searchConfig || []" @searchCallBack="searchCallBack"
            v-show="multipleSelection.length == 0"></ISearch>
          <!-- 操作按钮组 -->
          <div v-show="multipleSelection.length != 0">
            <el-button type="primary" style="background-color: #f1edf0; color: #714B67;">
              {{ "(" + multipleSelection.length + ") 已选取" }}
            </el-button>
            <el-dropdown trigger="click" popper-class="operation-dropdown" @command="handleOperationCommand">
              <el-button type="primary">
                <el-icon>
                  <Tools />
                </el-icon> 操作 <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="delete">删除</el-dropdown-item>
                  <el-dropdown-item command="export">导出</el-dropdown-item>
                  <el-dropdown-item command="archive">归档</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <!-- 按钮组-->
        <IdooButtonGroup :buttonConfigs="buttonGroupDatas" @clickCallBack="buttonGroupChange" is-active-style />
      </div>
    </div>
    <!-- 分割线 -->
    <el-divider border-style="dotted" />

    <div style="display: flex; height: 100vh;">
      <!-- 表格列表 -->
      <div style="display: flex;flex-direction: column; height: auto;position: relative; width: 100%;flex: 1;">
        <el-table ref="multipleTableRef" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
          @row-click="(row: DepartmentForm) => router.push({ path: '/employess-department-list/add', query: { id: row.id } })">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="deptName" label="部门名称" width=400 />
          <el-table-column prop="pDeptName" label="上级部门" width=400 />
          <el-table-column prop="deptLevelPath" label="部门层级" width=600 />
          <el-table-column prop="deptStaffCount" label="员工数量" width=100 />
          <el-table-column prop="deptChildrenCount" label="子部门数量" width=100 />
          <el-table-column prop="deptManager" label="负责人" sortable />
        </el-table>
        <!-- 卡片列表 -->
        <div style="width: 100%;" v-if="showType == 'card'">
          <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            <div v-for="cardItem in cardData" :key="cardItem.id" class="card">
              <el-card>
                <div style="width: 100%; height: 100px;">
                  <el-row>
                    <span>{{ cardItem.deptName }} ;</span>
                  </el-row>
                  <el-row>
                    <el-button type="primary"
                      style="width: 70px;margin-top: 26px; margin-left: 15px; margin-bottom: 8px;">
                      {{ cardItem.staffCount }} 员工</el-button>
                  </el-row>
                </div>
              </el-card>
            </div>
          </div>
        </div>
        <!-- 分页 -->
        <div style="margin-top: 5px; margin-bottom: 5px;" v-if="tableData.length > 0">
          <IdooPagination :param="initPaginationParam" style="float:right ;margin-right: 25px;"
            @click-call-back="paginationCallBack"></IdooPagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue';
import IdooPagination from '@/components/base/pagination/index.vue'
import { Tools } from '@element-plus/icons-vue'
import ISearch from '@/components/base/search/index.vue'
import { buttonGroupData, type DepartmentData } from './testData';
import IdooButtonGroup from '@/components/base/button/buttonGroup/index.vue'
import type { ButtonGroupStructure } from '@/components/base/button/buttonGroup';
import type { PaginationStructure } from '@/components/base/pagination';
import { OrderEnums } from '@/types/wrapper-enums';
import type { QueryCondition, QueryPage, QueryWrapper } from '@/types/wrappertypes';
import type { TableFieldType } from '@/types/table-configtypes';
import type { DepartmentForm } from '@/types/employess/department/types';
import { _delDepartmentInfoByIds, _getDepartmentTableConfigeration, _getDepartmentTableList } from '@/api/generic/employess/department/list-api';
import router from '@/router';
//展示方式  list\card
const showType = ref<string>('list')
//列表勾选得内容
const multipleSelection = ref<DepartmentForm[]>([]);
//按钮组数据
const buttonGroupDatas = buttonGroupData;
const tableData = ref<DepartmentForm[]>([]);
//多功能搜索框内容配置
const searchConfig = ref<TableFieldType[]>([]);
//表格列内容配置
const tableColumnConfig = ref<TableFieldType[]>([]);

//初始化分页参数
const initPaginationParam = ref<PaginationStructure>({ pageNum: 1, pageSize: 20, startNum: 1, totalNum: 0 });
//初始化查询条件
const queryWrapperCondition = ref<QueryWrapper>({
  page: initPaginationParam.value,//分页参数
  condition: [], //数据参数
  sort: [{ filed: 'dept_level_path', orderType: OrderEnums.WRAPPER_ORDER_ASC }] //排序参数
});
//表格勾选
const handleSelectionChange = (val: []) => {
  console.log(val);
  multipleSelection.value = val
}
const cardData = ref<DepartmentData[]>([]);

//搜索框回调
const searchCallBack = (callbackItem: QueryCondition[]) => {
  console.log("搜索回调", callbackItem)
  initPaginationParam.value.startNum = 1
  initPaginationParam.value.pageNum = 1
  queryWrapperCondition.value.page = initPaginationParam.value;
  queryWrapperCondition.value.condition = callbackItem;
  console.log("wrapper:", queryWrapperCondition.value)
  refreshTableData();
}
//分页组件回调
const paginationCallBack = (obj: QueryPage) => {
  console.log(obj);
  if (initPaginationParam.value && obj.pageNum !== undefined) {
    initPaginationParam.value.pageNum = obj.pageNum;
    initPaginationParam.value.startNum = (obj.pageNum - 1) * initPaginationParam.value.pageSize + 1;
  }
  refreshTableData();
}
//新增角色
const add = () => {
  router.push({
    path: '/employess-department-list/add'
  })
}
const handleOperationCommand = async (command: string) => {
  console.log("操作命令:", command);
  console.log("选中的数据", multipleSelection.value)
  // 根据不同命令执行相应操作
  if (command === "delete") {
    // TODO: 删除操作逻辑
    if (multipleSelection.value) {
      const delIds = multipleSelection.value.map(item => item.id)
      const res = await _delDepartmentInfoByIds(delIds.join(','));
      if (res.code === 200) {
        refreshTableData();
      }
    }
  } else if (command === "export") {
    // TODO: 导出操作逻辑
  } else if (command === "archive") {
    // TODO: 归档操作逻辑
  }
}

//按钮组回调
const buttonGroupChange = (callbackItem: ButtonGroupStructure) => {
  console.log(callbackItem)
  showType.value = callbackItem.id;
  resetViewData();
}

const resetViewData = () => {
  //清空表格勾选数组
  multipleSelection.value = [];
}
onMounted(async () => {
  //获取列表页配置项
  const configer = await _getDepartmentTableConfigeration();
  console.warn(configer);
  if (configer.code == 200) {
    const res = configer.data;
    searchConfig.value = res.selectorFieldsConfig || [];
    tableColumnConfig.value = res.tableColumnsConfig || [];
  }
  nextTick(() => {
    refreshTableData();
  });
  //构造卡片数据
  // tableData.map(item => {
  //   const a: DepartmentData = {
  //     ...item,
  //     id: item.id || '',
  //     staffCount: Number(item.staffCount)
  //   }
  //   cardData.value.push(a);
  // })
});


const refreshTableData = async () => {
  console.log("wrapper:", queryWrapperCondition.value);
  try {
    const res = await _getDepartmentTableList(queryWrapperCondition.value);
    console.log(res);
    if (res.code == 200 && res.message == 'success') {
      tableData.value = Array.isArray(res.data.rows) ? res.data.rows : [res.data.rows];
      if (initPaginationParam.value) {
        initPaginationParam.value.totalNum = res.data.total;
      }
      console.error(initPaginationParam.value);
    }
  } finally { }
}
</script>

<style scoped>
:deep(.el-divider--horizontal) {
  margin: 20px 0px 0px !important;
}

.main-left-area {
  border-right: 1px solid #dcdfe6;
  width: 300px;
  min-height: 400px;
  overflow: outo;
}

.card {
  flex-basis: 400PX;
  /* 考虑 10px 的间隙，每个卡片占 20% 宽度 */
  height: 110px;
  box-sizing: border-box;
}


:deep(.el-card__body) {
  justify-content: normal !important;
  align-items: normal m !important
}

.search-operation-container {
  height: 32px;
  display: flex;
  align-items: center;
}
</style>
